package com.caiyigo.baihua.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.sageras.util.ExcelUtil.ExcelLog;
import org.sageras.util.ExcelUtil.ExcelLogs;
import org.sageras.util.ExcelUtil.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.asprise.util.ocr.OCR;
import com.caiyigo.baihua.Const.Const;
import com.caiyigo.baihua.dto.DataGrid;
import com.caiyigo.baihua.dto.KaoshicjDto;
import com.caiyigo.baihua.dto.Pager;
import com.caiyigo.baihua.dto.Result;
import com.caiyigo.baihua.dto.XueshengDto;
import com.caiyigo.baihua.model.SystemUser;
import com.caiyigo.baihua.model.Xuesheng;
import com.caiyigo.baihua.service.KaoshicjService;
import com.caiyigo.baihua.service.XueshengService;
import com.caiyigo.baihua.shiro.ShiroExt;
import com.github.miemiedev.mybatis.paginator.domain.Order;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;

/**
 * @author Administrator
 * 
 */
@Controller
@RequestMapping(value = "/business/xuesheng")
public class XueshengController {
	@Autowired
	XueshengService xueshengService;
	@Autowired
	KaoshicjService kaoshicjService;

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public @ResponseBody DataGrid<XueshengDto> list(XueshengDto xueshengDto,
			Pager page) {
		List<Order> orders = new ArrayList<Order>();
		orders.add(Order.create(page.getSort(), page.getOrder()));
		PageList<XueshengDto> pageList = (PageList<XueshengDto>) xueshengService
				.getUserList(xueshengDto,
						new PageBounds(page.getPage(), page.getRows(), orders,
								true));
		return new DataGrid<XueshengDto>(pageList.getPaginator()
				.getTotalCount(), pageList.getPaginator().getPage(), pageList);

	}

	@RequestMapping(value = "/export", method = RequestMethod.GET)
	public void export(XueshengDto xueshengDto, Pager page,
			HttpServletResponse response) throws ClientProtocolException,
			IOException, InterruptedException {
		response.setCharacterEncoding("UTF-8");
		String fileName = "baihua-xuesheng-" + System.currentTimeMillis()
				+ ".xls";
		List<XueshengDto> XueshengDtopageList = xueshengService.getUserList(
				xueshengDto, new PageBounds());
		response.setHeader("Content-Disposition", "inline; filename="
				+ fileName);
		// 确保发送的当前文本格式
		response.setContentType("application/vnd.ms-excel");
		try {
			ExcelUtil.exportExcel("百花教育学生信息表", XueshengDtopageList,
					response.getOutputStream(), XueshengDto.class);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public @ResponseBody Result importExcel(
			@RequestParam(value = "file", required = true) MultipartFile file) {

		Map<String, Xuesheng> xueshengs = xueshengService.getAll();
		ExcelLogs logs = new ExcelLogs();
		Collection<Xuesheng> list = null;

		try {
			list = ExcelUtil.importExcel(Xuesheng.class, file.getInputStream(),
					logs, 2);
		} catch (IOException e) {
			return new Result(false, "导入失败");
		}

		List<OtherResult> message = new ArrayList<OtherResult>();
		for (ExcelLog excelLog : logs.getErrorLogList()) {
			message.add(new OtherResult(String.valueOf(excelLog.getRowNum()),
					excelLog.getLog()));
			System.out.println(excelLog.getSheetIndex() + ":"
					+ excelLog.getRowNum() + "：" + excelLog.getLog());
		}
		if (message.size() == 0) {
			List<Xuesheng> flagList = new ArrayList<Xuesheng>();
			for (Xuesheng student : list) {
				if (null == xueshengs.get(student.getZkz())) {
					flagList.add(student);
					continue;
				}
				if (!xueshengs.get(student.getZkz()).equals(student)) {
					student.setId(xueshengs.get(student.getZkz()).getId());
					flagList.add(student);
				}
			}
			if (flagList.size() > 0) {
				xueshengService.batchUpdate(flagList);
			}
			return new Result(true);
		} else {
			return new Result(false, message);
		}

	}

	@RequestMapping(value = "/select", method = RequestMethod.POST)
	public @ResponseBody DataGrid<XueshengDto> select(XueshengDto xueshengDto,
			DataGrid<XueshengDto> dataGrid) {
		List<Order> orders = new ArrayList<Order>();
		orders.add(Order.create(dataGrid.getSort(), dataGrid.getOrder()));
		PageList<XueshengDto> pageList = (PageList<XueshengDto>) xueshengService
				.getUserList(xueshengDto, new PageBounds(1, 11, orders, true));
		dataGrid.setPage(pageList.getPaginator().getPage());
		dataGrid.setRows(pageList);
		return dataGrid;
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Result delete(
			@RequestParam(value = "id", required = true) Integer id) {

		return new Result(xueshengService.deleteByPrimaryKey(id) > 0);

	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public @ResponseBody Result add(
			@ModelAttribute("user") XueshengDto xueshengDto) {
		SystemUser user = (SystemUser) ShiroExt
				.getSessionAttr(Const.SESSION_USER);
		xueshengDto.setAddby(user.getId() + "");
		xueshengDto.setAddtime(new Date());

		return new Result(xueshengService.insertSelective(xueshengDto) > 0);

	}

	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public @ResponseBody Result edit(
			@ModelAttribute("user") XueshengDto xueshengDto) {

		return new Result(
				xueshengService.updateByPrimaryKeySelective(xueshengDto) > 0);

	}

	@RequestMapping(value = "/batchDelete", method = RequestMethod.GET)
	public @ResponseBody Result batchDelete(
			@RequestParam(value = "ids", required = false) String id) {
		String[] idArray = id.split(",");

		return new Result(xueshengService.batchDelete(idArray) > 0);

	}

	@RequestMapping(value = "/getAllCjByZyidAndXsid", method = RequestMethod.GET)
	public @ResponseBody List<KaoshicjDto> getAllCjByZyidAndXsid(
			@RequestParam(value = "id", required = false) Integer id) {
		Xuesheng xuesheng = xueshengService.selectByPrimaryKey(id);
		return kaoshicjService.getAllCjByZyidAndXsid(xuesheng);

	}

}
